package leetcode.f1t100;

/**
 * 计数并输出
 * 1
 * 11
 * 21
 * 1211
 * 111221
 * https://leetcode.com/problems/count-and-say/
 *
 * @Author lichongxiao
 * @Date 2022/10/12 14:18
 */
public class Q38_CountAndSay {
    public String countAndSay(int n) {
        if (n == 1) {
            return "1";
        }
        char[] chars = countAndSay(n - 1).toCharArray();
        int times = 1, length = chars.length;
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < length; i++) {
            if (chars[i] == chars[i - 1]) {
                times++;
            } else {
                sb.append(times);
                sb.append(chars[i - 1]);
                times = 1;
            }
        }
        sb.append(times);
        sb.append(chars[length - 1]);
        return sb.toString();
    }

    public String countAndSay1(int n){
        String ans = "1";
        for (int i = 1; i < n; i++) {
            char[] chars = ans.toCharArray();
            int times = 1, length = chars.length;
            StringBuilder sb = new StringBuilder();
            for (int j = 1; j < length; j++) {
                if (chars[j] == chars[j - 1]) {
                    times++;
                } else {
                    sb.append(times);
                    sb.append(chars[j - 1]);
                    times = 1;
                }
            }
            sb.append(times);
            sb.append(chars[length - 1]);
            ans = sb.toString();
        }
        return ans;
    }

    public static void main(String[] args) {
        Q38_CountAndSay bean = new Q38_CountAndSay();
        for (int i = 1; i < 10; i++) {
            String s1 = bean.countAndSay(i);
            String s2 = bean.countAndSay1(i);
            if(!s1.equals(s2)){
                System.out.println("fail");
                System.out.println(s1);
                System.out.println(s2);
                return;
            }
        }
        System.out.println("success");
    }
}
